import requests
from flask import Flask, request, jsonify, abort
from flask_cors import CORS

from db.sqlite.face_vector import FaceVector
from db.sqlite.sqlite import SQLiteDB
from insightface.insightface import InsightFace
from utils.image_utils import check_image
import numpy as np

app = Flask(__name__)
# 初始化CORS，并将其应用到整个应用上，允许所有域名的请求
CORS(app, resources={r"/*": {"origins": "*"}})


@app.route('/detection_face', methods=['POST'])
def detection_face():
    detection_faces = get_detection_faces('image')

    # 读取数据库中的人脸
    db = SQLiteDB()
    face_list = FaceVector.select_list(db)
    db.close()

    # 比对人脸特征(欧式距离)
    nearest_index, score = model.compute_nearest_neighbor(detection_faces,
                                                          [np.frombuffer(tup[2], dtype=np.float32) for tup in
                                                           face_list])

    if score >= 1:
        return jsonify({'code': 1002, 'msg': '未匹配到'}), 200

    return jsonify({'code': 200, 'msg': '检测成功', 'data': face_list[nearest_index][1]}), 200


@app.route('/compare_face', methods=['POST'])
def compare_face():
    detection_faces_1 = get_detection_faces('image1')
    detection_faces_2 = get_detection_faces('image2')
    _, score = model.compute_nearest_neighbor(detection_faces_1[0], detection_faces_2)
    return jsonify({'code': 200, 'msg': '对比成功', 'data': float(score)}), 200



def get_detection_faces(image_name):
    # 获取上传的图片文件
    image_file = request.files.get(image_name)
    # 检查文件是否有效且为图像类型
    if image_file and check_image(image_file.filename):
        # 将图片文件内容转为字节流
        image_data = image_file.read()
        # 调用专门处理图片的方法
        img, faces = model.load_and_process_image_from_stream(image_data)
        detection_faces = model.extract_face_features(faces)
        if len(detection_faces) == 0:
            abort(jsonify({'code': 1001, 'msg': '未检测到人脸'}), 200)
        return detection_faces
    abort(jsonify({'code': 500, 'msg': '图片格式不正确'}), 500)


# 在应用初始化阶段创建模型
if __name__ == '__main__':
    # 启动一个本地开发服务器，激活该网页
    model = InsightFace()
    app.run(host='0.0.0.0', port=8888)
